#include "vis_draw.h"
#include "ui_vis_draw.h"
#include "vis_sdk.h"
#include <cmath>
#include <cstring>
vis_draw::vis_draw(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::vis_draw)
{
    ui->setupUi(this);
    ui->area->setScene(&scene);
    this->setWindowTitle(tr("Visualiser"));
    this->wave_len = this->fft_len = 0;
    this->wave = NULL;
    this->fft = NULL;
    _SPEC_HEIGHT = 0;
    memset(fft_falloff, 0, sizeof(fft_falloff));
    memset(fft_peaks, 0, sizeof(fft_peaks));
    px = new QPixmap(ui->area->width(), ui->area->height());
}


void vis_draw::spectrum_draw_frame(int x, int y)
{
    px->fill();
    QPainter pt(px);
    pt.setBackground(QBrush(Qt::black));
    pt.setBrush(QBrush(Qt::black));
    for (int i = 0; i < 10; i++)
    {
        float yval = fft[i * _VIS_DRAWRES + 5];
        int ypos = fabs(floor(yval * 500.0));
        if (ypos > _SPEC_HEIGHT)
            _SPEC_HEIGHT = ypos;
        if (ypos >= fft_peaks[i])
            fft_peaks[i] = ypos;
        else
            fft_peaks[i] -= _SPEC_PEAKFALL;

        if (ypos >= fft_falloff[i])
            fft_falloff[i] = ypos;
        else
            fft_falloff[i] -= _SPEC_LINEFALL;

        fft_peaks[i] = fmax(fft_peaks[i], 0);
        fft_falloff[i] = fmax(fft_falloff[i], 0);
        if (_VIS_DRAWTYPE == 0)
        {
            pt.setPen(Qt::green);
            pt.setBrush(QBrush(Qt::green));
            pt.drawLine(x + i, y + px->height(), x + i, y + px->height() - fft_falloff[i]);
           // qDebug("Drawing Line %d %d %d %d", x + i, y + px->height(), x + i, y + px->height() - fft_falloff[i]);
        }
        else
        {
            if (_SPEC_SHOW_PEAKS)
            {
                pt.setPen(Qt::yellow);
                pt.drawLine(x + i * (_SPEC_COLWIDTH + 1), y + px->height() - fft_peaks[i]
                            , x + i * (_SPEC_COLWIDTH + 1) + _SPEC_COLWIDTH, y + px->height() - fft_peaks[i]);

            }
            pt.setPen(Qt::green);
            pt.setBrush(QBrush(Qt::green));
            pt.drawRect(x + i * (_SPEC_COLWIDTH + 1), y + px->height() - fft_falloff[i],
                        x + i * (_SPEC_COLWIDTH + 1) + _SPEC_COLWIDTH, y + px->height());
        }

    }
  //  pt.drawRect(QRect(0, 0, px->width() - 1, px->width() - 1));
    //pt.save();
    pt.end();
    //pt.setViewport();

}

void vis_draw::init(unsigned *wave, float *fft, int wave_len, int fft_len)
{
    this->wave = wave;
    this->fft = fft;
    this->wave_len = wave_len;
    this->fft_len = fft_len;
}

void vis_draw::d_repaint()
{
    spectrum_draw_frame(0, 10);
    scene.addPixmap(*px);
    repaint();
}

vis_draw::~vis_draw()
{
    delete px;
    delete ui;
}
